//
//  MyGroupViewController.swift
//  Venus
//
//  Created by qurongxiang on 2018/9/8.
//  Copyright © 2018年 zhaowang. All rights reserved.
//

import UIKit
import MJRefresh

private let kCellID = "kAdminGroupCellId"

class MyGroupAdminListVC: BaseViewController {
    
    fileprivate var pageNo : Int = 1
    fileprivate var pageSize : Int = 10
    
    var groupModel : TopicGroupModel?
 
    var groupList:[TopicGroupModel] = [TopicGroupModel]()
    
    lazy var tableView : UITableView = {
        let tableView = UITableView(frame: CGRect.zero)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
//        tableView.register(UINib(nibName: "TopicMyGroupTableViewCell", bundle: nil), forCellReuseIdentifier: kCellID)
//        tableView.register(UITableViewCell.self, forCellReuseIdentifier: kCellID)

        return tableView
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "管理员"
        setupUI()
        
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    public func configModel(model:TopicGroupModel){
        
        groupModel = model
        
        title = model.groupName
        
    }
    
    @objc func rightItemDidClick(item:UIButton) -> Void {
        let vc:AddAdminViewController  = AddAdminViewController.init(nibName: nil, bundle: nil)
        vc.groupId = (groupModel?.id)!
        vc.groupVC = self;
        navigationController?.pushViewController(vc, animated: true)
    }
    
    public func loadData(){
        
        guard let gModel = groupModel else {
            return
        }
        
        self.hudLoad()

        let dict = [
            "operatorId":String(UserInfo.shareInstance.userModel().id),
            "groupId":String(gModel.id),
            "pageNo":self.pageNo,
            "pageSize":self.pageSize,
            "sign" : 1,
            "timestamp" : 1] as [String : Any]
        
        TempNetTool.get( kHost + kqueryGroupAdminList, parameters: dict, progress: nil, success: { [weak self] (result) in
            self?.tableView.mj_header.endRefreshing()
            self?.tableView.mj_footer.endRefreshing()
            if (self?.pageNo == 1) {
                self?.groupList.removeAll()
            }
            if (result != nil) {
                guard let resultDict = result as? [String : NSObject] else { return }
                guard let dataArray = resultDict["data"] as? [NSObject] else { return }
                let groupModels = TopicGroupModel.tmSpeelBreakModelArr(dataArray)
                if (groupModels.count < (self?.pageSize)!){
                    self?.tableView.mj_footer.endRefreshingWithNoMoreData()
                }
                let gourpModels1  = (groupModels as? [TopicGroupModel])?.filter{(topicModel) -> Bool in
                    return topicModel.user != nil
                }
                
                self?.groupList.append(contentsOf: (gourpModels1)!)
                
                self?.tableView.reloadData()
            }
            self?.hudHide()
            
            
        }) {[weak self]   (error) in
            self?.hudHide()
            self?.tableView.mj_header.endRefreshing()
            self?.tableView.mj_footer.endRefreshing()
            
        }
        
    }
}


extension MyGroupAdminListVC:UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.groupList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: kCellID, for: indexPath)
//        cell.configModel(model: self.groupList[indexPath.item], index: indexPath)
        let cell: UITableViewCell = {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: kCellID) else {
                // Never fails:
                return UITableViewCell(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: kCellID)
            }
            return cell
            
        }()
        for guester : UIGestureRecognizer in cell.contentView.gestureRecognizers! {
            if guester.classForCoder == UILongPressGestureRecognizer.classForCoder(){
                cell.contentView.removeGestureRecognizer(guester)
            }
        }
        
        let longpress : UILongPressGestureRecognizer = UILongPressGestureRecognizer.init(target: self, action: #selector(didLongPress(longPress:)))
        cell.contentView.addGestureRecognizer(longpress)
        let model = groupList[indexPath.row];
        cell.textLabel?.text = (model.user!["userName"] as! String);
        cell.textLabel?.font = UIFont.systemFont(ofSize: 18)
        cell.detailTextLabel?.text = String.timeToString(time: (model.user?["updateTime"] as! NSString).integerValue)
        cell.detailTextLabel?.textColor = UIColor.gray
        cell.imageView!.kf.setImage(with: URL(string: model.user!["headImg"] as! String), placeholder: UIImage.init(named: "defalut_avatar"), options: [.cacheMemoryOnly], progressBlock: nil, completionHandler: { (image, error, type, url) in
        
        })
        cell.imageView?.contentMode = .center
        cell.imageView?.layer.masksToBounds = true
        cell.selectionStyle = .none
        cell.imageView?.layer.cornerRadius = (cell.imageView?.image?.size.height)!/2
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
//        tableView.deselectRow(at: indexPath, animated: false)
//        let model = self.groupList[indexPath.item]
//        let vc = GroupTopicViewController()
//        vc.configModel(model: model);
//        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func didLongPress(longPress:UILongPressGestureRecognizer) {
        let cell = longPress.view?.superview as? UITableViewCell
        let index = tableView.indexPath(for: cell!);
        let model = self.groupList[(index?.row)!]
        if longPress.state == .recognized {
            let alert = UIAlertController.init(title: nil, message: "删除该管理员？", preferredStyle: .actionSheet)
            let action1 = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
            let action2 = UIAlertAction.init(title: "确定", style: .default) { [weak self] (action) in
                self?.removeModel(id: model.userId, compeletion: { [weak self] in
                    self?.groupList.remove(at: (index?.row)!);
                    self?.tableView.reloadData()
                })
            }
            alert.addAction(action1)
            alert.addAction(action2)
            self.present(alert, animated: true, completion: nil)
        }
        
    }
    
    
    func removeModel(id : Int,compeletion:@escaping ()->()){
        let dict = [ "groupId" : groupModel?.groupId,
                     "operatorId" : UserInfo.shareInstance.userModel().id,
                     "userId" : id,
                     "timestamp" : 1,
                     "sign" : 1
        ] as [String : Any]
        
        NetworkTools.shareInstance.loadData(.post, URLString: kdeleteAdminToGroupList, parameters: dict) { (response, isReslut) in
            if !isReslut {
                compeletion()
            }
        }
    }

}


extension MyGroupAdminListVC {
    fileprivate func setupUI(){
        
        view.backgroundColor = UIColor.white
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(LayoutCommon.navHeight)
            make.left.right.equalToSuperview()
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalTo(view.snp.bottom)
            }
        }
        
        
        tableView.tableFooterView = UIView(frame: CGRect.zero);
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.pageNo = 1
            self.loadData()
        })
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            self.pageNo += 1
            self.loadData()
        })
        tableView.mj_header.beginRefreshing()
        
        let btn = UIButton.init()
        btn.setImage(UIImage.init(named: "nav_create"), for: .normal)
        btn.imageView?.contentMode = .center
        navgationBar.addSubview(btn)
        btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-8)
            make.width.equalTo(44)
            make.height.equalTo(44)
            make.bottom.equalToSuperview()
        }
        btn.addTarget(self, action: #selector(rightItemDidClick(item:)), for: .touchUpInside)
    }
    
}
